/**
 * @filename:CapitalTypeServiceImpl 2023-4-20
 * @project Wonder Java前后台分离框架  1.1.0
 * Copyright(c) 2022 Wonder Co. Ltd.
 * All right reserved.
 */
package com.wonder.app.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.admin.service.IVtuzxKingdeeService;
import com.wonder.admin.service.impl.VtuzxKingdeeServiceImpl;
import com.wonder.app.domain.*;
import com.wonder.app.mapper.MoldAndInspectDao;
import com.wonder.app.mapper.MoldInspectDao;
import com.wonder.app.mapper.MoldMaintenanceDao;
import com.wonder.app.mapper.MoldMaterialDao;
import com.wonder.app.request.MoldAndInspectRequest;
import com.wonder.app.request.MoldInspectRequest;
import com.wonder.app.service.*;
import com.wonder.bean.kingdee.VtuzxKingdeeCloudClient;
import com.wonder.bean.kingdee.xqc.VtuzxArrayList;
import com.wonder.common.utils.MapToEntity;
import com.wonder.constant.BillType;
import com.wonder.constant.IXqcConst;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Description:TODO(模具链类型服务实现)
 *
 * @version: 1.1.0
 * @author: Wonder
 *
 */
@Service

public class MoldInspectServiceImpl extends ServiceImpl<MoldInspectDao, MoldInspect> implements MoldInspectService {
    /** 日志 */
    private static final Logger _logger = LoggerFactory.getLogger(MoldInspectServiceImpl.class);
    @Autowired
    private MoldInspectService moldInspectService;
    @Autowired
    private MoldInspectDao moldInspectDao;
    @Autowired
    private MoldMaterialService moldMaterialService;
    @Autowired
    private MoldAndInspectService moldAndInspectService;
    @Autowired
    private MoldMaintenanceService moldMaintenanceService;
    @Autowired
    private MoldScrapService moldScrapService;
    @Autowired
    private IVtuzxKingdeeService vtuzxKingdeeService;
    @Autowired
    private MoldMaterialDao moldMaterialDao;

    @Autowired
    private SyncKingdeeOrderService syncKingdeeOrderService;


    @Override
    public String validate(MoldInspect moldInspect, String type) {
        return "";
    }

    @Override
    public IPage<MoldInspect> selectList(MoldInspectRequest request, Page<MoldInspect> page) {
        LambdaQueryWrapper<MoldInspect> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if (null != request.getId()) {
            lambdaQueryWrapper.eq(MoldInspect::getId, request.getId());
        }
        if (request.getBillNo() != null){
            lambdaQueryWrapper.like(MoldInspect::getBillNo,request.getBillNo());
        }
        if (request.getMaterialNo() != null){
            lambdaQueryWrapper.like(MoldInspect::getMaterialNo,request.getMaterialNo());
        }
        if (request.getMaterialName() != null){
            lambdaQueryWrapper.like(MoldInspect::getMaterialName,request.getMaterialName());
        }
        if (request.getStockNo() != null){
            lambdaQueryWrapper.like(MoldInspect::getStockNo,request.getStockNo());
        }
        if (request.getStockName() != null){
            lambdaQueryWrapper.like(MoldInspect::getStockName,request.getStockName());
        }
        if (request.getLocationName() != null){
            lambdaQueryWrapper.like(MoldInspect::getLocationName,request.getLocationName());
        }
        if (request.getLocationNo() != null){
            lambdaQueryWrapper.like(MoldInspect::getLocationNo,request.getLocationNo());
        }
        if (request.getCreateUserName() != null){
            lambdaQueryWrapper.like(MoldInspect::getCreateUserName,request.getCreateUserName());
        }

        if (request.getCreateTime() != null){
            Date[] orderDate = request.getCreateTime();
            if(orderDate.length>0)
                lambdaQueryWrapper.ge(MoldInspect::getCreateTime, orderDate[0]);
            if(orderDate.length==2)
                lambdaQueryWrapper.le(MoldInspect::getCreateTime,orderDate[1]);

        }
        lambdaQueryWrapper.orderByDesc(MoldInspect::getId);
        Page<MoldInspect> selectPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);
        return selectPage;
    }

    /**
     * 模具检查单
     * @param userName
     * @param moldMaterial
     * @return
     */
    @Override
    public boolean createInspect(String userName, MoldMaterial moldMaterial){
        String BILLNO =  IXqcConst.createBillNo(BillType.MJJC);//生成模具检查单号
        MoldInspect moldInspect = new MoldInspect();
        moldInspect.setBillNo(BILLNO);
        moldInspect.setCreateTime(new Date());
        moldInspect.setCreateUserName(userName);
        moldInspect.setMoldId(Math.toIntExact(moldMaterial.getId()));
        moldInspect.setMaterialName(moldMaterial.getMaterialName());
        moldInspect.setMaterialNo(moldMaterial.getMaterialNo());
        moldInspect.setStockNo(moldMaterial.getStockNo());
        moldInspect.setStockName(moldMaterial.getStockName());
        moldInspect.setLocationNo(moldMaterial.getLocationNo());
        moldInspect.setLocationName(moldMaterial.getLocationName());
        moldInspect.setStatus(1);//1是待检
        moldInspect.setMoldStatus(0);//无状态


        return moldInspectService.saveOrUpdate(moldInspect);

    }

    /**
     * 修改单据状态
     * @param userName
     * @param map
     * @return
     */
    @Override
    public boolean updateStatus(String userName, Map<String, Object> map){
        String BillNo = VtuzxUtil.getString(map,"BillNo");
        int status = VtuzxUtil.getInt(map,"status");
        //获取模具检修单数据
        MoldInspect moldInspect = moldInspectDao.selectOne(new LambdaQueryWrapper<MoldInspect>().eq(MoldInspect::getBillNo,BillNo));
        moldInspect.setStatus(status);

        return moldInspectService.saveOrUpdate(moldInspect);
    }

    /**
     * 检查单领料模具
     * @param map
     * @return
     */
    @Override
    public boolean moldInspectPickmold(String userName,Map<String, Object> map) throws Exception{
        //判断扫描的仓位和检查单中的仓位是否一致
        //一致的话将模具领出(修改模具状态)修改检查单的状态，添加模具链的信息
        String locationNo = VtuzxUtil.getString(map,"locationNo");
        Map<String,Object> inspectMap = VtuzxUtil.getObject(map,"inspectMap");
        MoldInspect moldInspect = MapToEntity.mapToBean(inspectMap,MoldInspect.class);
        String insLoctionNo = VtuzxUtil.getString(inspectMap,"locationNo");//检查单中的仓位
        if (!locationNo.equals(insLoctionNo)){
            throw new RuntimeException("扫描的仓位与检查单中的仓位不一致");
        }
        //判断模具是否在库
        MoldMaterial moldMaterial = moldMaterialDao.selectOne(new LambdaQueryWrapper<MoldMaterial>()
                .eq(MoldMaterial::getLocationNo, locationNo)
                .eq(MoldMaterial::getStatus, 0)//数据状态在库
                .eq(MoldMaterial::getInspectStatus, 2));//检查状态正常
        if(VtuzxUtil.isEmpty(moldMaterial)){
            throw new RuntimeException("模具不在库");
        }
        //修改模具状态为出库，检查状态为检查
        boolean updateMold = moldMaterialService.updateMoldStatus(moldMaterial,"检查出库");//修改模具状态
        //修改检查单的状态为检查中
        moldInspect.setStatus(2);
        moldInspectService.saveOrUpdate(moldInspect);

        //添加模具链信息
        Map<String,Object> insMap = new HashMap<>();
        insMap.put("moldId",moldMaterial.getId());
        insMap.put("orderNo",moldInspect.getBillNo());
        insMap.put("orderTime",moldInspect.getCreateTime());
        insMap.put("orderType",1);

        boolean inspectres = moldAndInspectService.createAndInspect(userName,insMap);//添加模具连


        return inspectres & updateMold;

    }

    /**
     * 检验单判断维修Or报废
     * @param userName
     * @param map
     * @return
     */
    @Override
    public boolean scrapOrMaintence(String userName,Map<String, Object> map){
        String orderType =VtuzxUtil.getString(map,"orderType");
        boolean res = false;
        if(orderType.equals("维修单")){
//           res = moldMaintenanceService.createMainTen(userName,map);
        } else if (orderType.equals("报废单")) {
//           res = moldScrapService.createScrp(userName,map);
        }
        return res;
    }

    /**
     * 模具检修单列表(手机端，只查询还未检修的单据)
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> getMoldInspectList(Map<String, Object> map) throws Exception {
        int pageIndex = VtuzxUtil.getInt(map,"pageIndex");
        int pageSize = VtuzxUtil.getInt(map,"pageSize");
        String billNo = VtuzxUtil.getString(map,"billNo");//订单号
        List<MoldInspect> dataList = moldInspectDao.getMoldInspectList(pageSize,pageIndex * pageSize,billNo);
        Map<String,Object> data = new HashMap<>();
        data.put("dataList",dataList);
        return data;
    }

    /**
     * 获取模具检查详情
     * @param map
     * @param user_id
     * @return
     */
    @Override
    public Map<String, Object> getMoldInspectDetail(Map<String, Object> map, Long user_id) throws Exception {
        String billNo = VtuzxUtil.getString(map,"billNo");
        MoldInspect moldInspect = moldInspectDao.selectOne(new LambdaQueryWrapper<MoldInspect>()
                .eq(MoldInspect::getBillNo, billNo));
        if (VtuzxUtil.isEmpty(moldInspect)){
            throw new RuntimeException("单号错误请重试");
        }
        Map<String,Object> data = new HashMap<>();
        data.put("data",moldInspect);

        return data;
    }

    /**
     * 审核模具检查单
     * @param userName
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Boolean auditMoldInspect(Long user_id,String userName, Map<String, Object> map) throws Exception {
        //模具状态是1正常，将模具归还，重置模具使用次数，修改检查单状态
        //模具状态3报废，修改模具状态，生成调拨单，调拨单报废仓，修改检查单状态，添加模具链
        //模具状态2维修，生成维修单(属性是外购不允许大修),添加模具链,修改检查单状态
        MoldInspect moldInspect = MapToEntity.mapToBean(map,MoldInspect.class);
        int moldStatus = moldInspect.getMoldStatus();//检查单中的模具状态
        int moldId = moldInspect.getMoldId();
        MoldMaterial moldMaterial = moldMaterialDao.selectById(moldId);
        if(moldStatus == 1){//检查正常
            //修改模具状态
            moldMaterialService.updateMoldStatus(moldMaterial,"检查正常");
            moldInspect.setStatus(3);
        } else if (moldStatus == 2){//维修
            //属性是外购不允许大修
            int category = moldInspect.getCategory();//0小修，1大修
            int erpCl = moldMaterial.getErpCl();//物料属性(1外购，2自制)
            if (erpCl == 1 && category == 1){
                throw new RuntimeException("物料属性是外购的不允许大修");
            }
            //大修的需要在金蝶创建一个生产订单
            if (category == 1){
                try {
                    syncKingdeeOrderService.syncPrdOrderMold(user_id,userName,moldInspect);
                } catch (Exception e){
//                    _logger.info(e.getMessage());
                    throw new RuntimeException(e.getMessage());
                }
            }

            //修改模具状态为维修
            moldMaterialService.updateMoldStatus(moldMaterial,"检查维修");
            //生成维修单(添加模具链)
            moldMaintenanceService.createMainTen(moldInspect,moldId,userName);
            //调整检查单状态
            moldInspect.setStatus(3);


        } else if (moldStatus == 3){//报废
            //修改模具状态
            moldMaterialService.updateMoldStatus(moldMaterial,"检查报废");
            //生成报废单和调拨单(添加模具链信息)
            moldScrapService.createScrp(userName,moldInspect);
            //修改检查单
            moldInspect.setStatus(3);
        }
        boolean b = moldInspectService.updateById(moldInspect);
        return b;
    }

    @Override
    public Map<String, Object> getmoldloDetail(Map<String, Object> map) {
        String locationNo = map.get("locationNo").toString();
        List<MoldMaterial> malList = moldMaterialDao.selectList(new LambdaQueryWrapper<MoldMaterial>()
                .eq(MoldMaterial::getLocationNo,locationNo));
        Map<String,Object> data = new HashMap<>();
        data.put("dataList",malList);
        // 修复点：确保永远返回 dataList 数组（即使为空）
        data.put("dataList", malList != null ? malList : Collections.emptyList());
        return data;

    }
    /**
     * 创建收料同通知单(web端)
     * @param userName
     * @param map
     * @return
     */
    @Override
    public Boolean createMoldInspect(String userName, Map<String, Object> map) {
        String materialNo = VtuzxUtil.getString(map,"materialNo");
        String materialName = VtuzxUtil.getString(map,"materialName");
        String locationNo = VtuzxUtil.getString(map,"locationNo");
        String locationName = VtuzxUtil.getString(map,"locationName");
        String stockNo = VtuzxUtil.getString(map,"stockNo");
        String stockName = VtuzxUtil.getString(map,"stockName");
        String billNo = IXqcConst.createMIBillNo(BillType.MJJC);
        //查询模具id
        MoldMaterial moldMaterial = moldMaterialDao.selectOne(new LambdaQueryWrapper<MoldMaterial>()
                .eq(MoldMaterial::getLocationNo, locationNo));
        if (VtuzxUtil.isEmpty(moldMaterial)){
            throw new RuntimeException("模具不存在");
        }
        Long id = moldMaterial.getId();
        MoldInspect moldinspect = new MoldInspect();
        moldinspect.setBillNo(billNo);
        moldinspect.setMaterialName(materialName);
        moldinspect.setMaterialNo(materialNo);
        moldinspect.setCreateTime(new DateTime());
        moldinspect.setCreateUserName(userName);
        moldinspect.setLocationName(locationName);
        moldinspect.setLocationNo(locationNo);
        moldinspect.setStatus(1);
        moldinspect.setStockName(stockName);
        moldinspect.setStockNo(stockNo);
        moldinspect.setMoldId(Math.toIntExact(id));
        boolean minspect = moldInspectService.save(moldinspect);
        return minspect;
    }

//    /**
//     * 修改模具检查单状态
//     * @return
//     */
//    private Boolean updateMoldaInspectStatus(MoldInspect moldInspect){
//        if (){
//
//        }
//
//    }

    /**
     * 检验改模具能欧大修
     * @param map
     * @return
     */
    @Override
    public boolean checkMainTen(Map<String,Object> map){
        int id = VtuzxUtil.getInt(map,"id");
        int erpCl = 0;
        MoldMaterial moldMaterial = moldMaterialService.getById(id);
        if(moldMaterial == null){
            throw new RuntimeException("未查询到模具数据");
        }else {
            erpCl = moldMaterial.getErpCl();
        }
        if(erpCl == 1){
            return false;
        }else{
            return true;
        }
    }
}
